package com.spider.im.login.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spider.im.common.aspect.BusinessException;
import com.spider.im.common.constant.RedisKey;
import com.spider.im.common.constant.RespCodeEnum;
import com.spider.im.login.resp.LoginUser;
import com.spider.im.user.entity.User;
import com.spider.im.user.resp.UserResp;
import com.spider.im.user.service.UserService;
import jakarta.annotation.Resource;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserService userService;

   @Resource
    private RedissonClient redissonClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        RBucket<UserResp> bucket = redissonClient.getBucket(RedisKey.USER_LOGIN_KEY + username);
        if (bucket.isExists()) {
            return new LoginUser(bucket.get());
        }
        List<User> userList = userService.list(new LambdaQueryWrapper<User>().eq(User::getUsername, username).or().eq(User::getPhone, username));
       if (CollectionUtil.isEmpty(userList)) {
           throw new BusinessException(RespCodeEnum.USER_NOT_EXIST);
       }
        User user = userList.get(0);
        UserResp userResp = new UserResp();
        BeanUtil.copyProperties(user, userResp);
        return new LoginUser(userResp);
    }
}